package com.example.spinnertest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private Spinner scope;
    private Spinner hero;
    private TextView t_rank,t_hero;
    private ImageView m_hero;

    private ArrayList<HeroBean> mData = null;   // 存放英雄的名字和图片的实体类数组

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView(){
        scope = findViewById(R.id.spinner_rank);
        hero = findViewById(R.id.spinner_hero);
        t_hero = findViewById(R.id.hero);
        t_rank = findViewById(R.id.rank);
        m_hero = findViewById(R.id.im_hero);

        mData = new ArrayList<HeroBean>();

        mData.add(new HeroBean(R.drawable.sunwukong,"孙悟空"));
        mData.add(new HeroBean(R.drawable.zixia,"紫霞仙子"));
        mData.add(new HeroBean(R.drawable.diaochan,"貂蝉"));
        mData.add(new HeroBean(R.drawable.hanxin,"韩信"));
        mData.add(new HeroBean(R.drawable.machao,"马超"));
        mData.add(new HeroBean(R.drawable.bailixuance,"百里玄策"));

        MyAdapter adapter = new MyAdapter(mData,this);  // 实例化适配器

        hero.setAdapter(adapter);   // 给 hero 设置适配器

        // 给选择段位的 spinner 添加监听
        scope.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                t_tank.setText(scope.getSelectedItem().toString());
            }

            @Override
            public void noNothingSelected(AdapterView<?> adapterView){

            }
        });

        //给选择英雄的spinner添加监听
        hero.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override //选中的时候执行的方法
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, mData.get(i).getName(), Toast.LENGTH_SHORT).show();
                t_hero.setText(mData.get(i).getName());//给TextView设置上选择的英雄名字
                m_hero.setImageResource(mData.get(i).getIcon());//给Imageview上选择的英雄图片
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }
}